package service

import (
	"GinShop/config"
	"GinShop/mapper"
	"GinShop/model"
	"GinShop/param"
	"GinShop/utils"
	"encoding/json"
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
	util "github.com/alibabacloud-go/tea-utils/service"
	"github.com/alibabacloud-go/tea/tea"
	"math/rand"
	"strconv"
	"strings"
	"time"
)

type MemberService struct {
}

func NewMemberService() *MemberService {
	return &MemberService{}
}

func (ms *MemberService) GetUserInfo(userId string) *model.Member {
	id, err := strconv.Atoi(userId)
	if err != nil {
		return nil
	}
	memberMapper := mapper.NewMemberMapper()
	return memberMapper.QueryMemberById(int64(id))
}

func (ms *MemberService) UploadAvatar(userId int64, fileName string) string {
	memberMapper := mapper.NewMemberMapper()
	result := memberMapper.UpdateMemberAvatar(userId, fileName)
	if result == 0 {
		return ""
	}

	return fileName
}

//用户登录
func (ms *MemberService) Login(name string, password string) *model.Member {

	//1、使用用户名 + 密码 查询用户信息 如果存在用户 直接返回
	md := mapper.NewMemberMapper()
	member := md.Query(name, password)
	if member.Id != 0 {
		return member
	}

	//2、用户信息不存在，作为新用户保存到数据库中
	user := model.Member{}
	user.UserName = name
	user.Password = utils.EncoderSha256(password)
	user.RegisterTime = time.Now().Unix()

	result := md.InsertMember(user)
	user.Id = result

	return &user
}

//用户手机号+验证码的登录
func (ms *MemberService) SmsLogin(loginparam param.SmsLoginParam) *model.Member {

	//1.获取到手机号和验证码

	//2.验证手机号+验证码是否正确
	md := mapper.NewMemberMapper()
	sms := md.ValidateSmsCode(loginparam.Phone, loginparam.Code)
	if sms.Id == 0 {
		return nil
	}

	//3、根据手机号member表中查询记录
	member := md.QueryByPhone(loginparam.Phone)
	if member.Id != 0 {
		return member
	}

	//4.新创建一个member记录，并保存
	user := model.Member{}
	user.UserName = loginparam.Phone
	user.Mobile = loginparam.Phone
	user.RegisterTime = time.Now().Unix()

	user.Id = md.InsertMember(user)

	return &user
}

func (ms *MemberService) Sendcode(phone string) bool {
	//1.产生一个验证码
	code := fmt.Sprintf("%04v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(10000))

	//2.调用阿里云sdk 完成发送
	sms := config.Config.Section("sms")
	appKey, err := sms.GetKey("AppKey")
	if err != nil {
		panic(err.Error())
	}
	appSecret, err := sms.GetKey("AppSecret")
	if err != nil {
		panic(err.Error())
	}

	par, err := json.Marshal(map[string]interface{}{
		"code": code,
	})
	res, err := _main(tea.StringSlice([]string{"阿里云短信测试", "SMS_154950909", phone, string(par), fmt.Sprintf("%s", appKey), fmt.Sprintf("%s", appSecret)}))
	//fmt.Println("------------->", res)
	//fmt.Println("============>", res.Body)
	//fmt.Println("``````````````````>", strings.Compare(*res.Body.Code, "OK"))
	if err != nil {
		return false
	}

	if strings.Compare(*res.Body.Code, "OK") == 0 {
		//将验证码保存到数据库中
		smsCode := model.SmsCode{Phone: phone, Code: code, BizId: *res.Body.BizId, CreateTime: time.Now().Unix()}
		memberMapper := mapper.NewMemberMapper()
		result := memberMapper.Create(&smsCode)
		return result.RowsAffected > 0
	}

	//3.接收返回结果，并判断发送状态
	//短信验证码发送成功
	return false
}

/**
 * 使用AK&SK初始化账号Client
 * @param accessKeyId
 * @param accessKeySecret
 * @return Client
 * @throws Exception
 */
func CreateClient(accessKeyId *string, accessKeySecret *string) (_result *dysmsapi20170525.Client, _err error) {
	conf := &openapi.Config{
		// 您的 AccessKey ID
		AccessKeyId: accessKeyId,
		// 您的 AccessKey Secret
		AccessKeySecret: accessKeySecret,
	}
	// 访问的域名
	conf.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	_result = &dysmsapi20170525.Client{}
	_result, _err = dysmsapi20170525.NewClient(conf)
	return _result, _err
}

func _main(args []*string) (res *dysmsapi20170525.SendSmsResponse, _err error) {
	client, _err := CreateClient(tea.String(*args[4]), tea.String(*args[5]))
	if _err != nil {
		return nil, _err
	}

	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		SignName:      tea.String(*args[0]),
		TemplateCode:  tea.String(*args[1]),
		PhoneNumbers:  tea.String(*args[2]),
		TemplateParam: tea.String(*args[3]),
	}
	runtime := &util.RuntimeOptions{}
	res, tryErr := func() (res *dysmsapi20170525.SendSmsResponse, _e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		// 复制代码运行请自行打印 API 的返回值
		res, _err := client.SendSmsWithOptions(sendSmsRequest, runtime)
		if _err != nil {
			return nil, _err
		}

		return res, nil
	}()

	if tryErr != nil {
		var error = &tea.SDKError{}
		if _t, ok := tryErr.(*tea.SDKError); ok {
			error = _t
		} else {
			error.Message = tea.String(tryErr.Error())
		}
		// 如有需要，请打印 error
		util.AssertAsString(error.Message)
		//if _err != nil {
		//	return _err
		//}
	}
	return res, _err
}
